package fr.sedoo.metadata.shared.domain.dto;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.TreeSet;

import com.google.gwt.user.client.rpc.IsSerializable;

import fr.sedoo.commons.client.util.SeparatorUtil;
import fr.sedoo.commons.client.util.StringUtil;

public class I18nString implements IsSerializable {

	/**
	 * defaultValue is only used for display. Never for edition.
	 */
	private String defaultValue;
	private HashMap<String, String> i18nValues = new HashMap<String, String>();

	public String getDefaultValue() {
		return defaultValue;
	}

	public void setDefaultValue(String defaultValue) {
		this.defaultValue = defaultValue;
	}

	public HashMap<String, String> getI18nValues() {
		return i18nValues;
	}

	public void setI18nValues(HashMap<String, String> i18nValues) {
		this.i18nValues = i18nValues;
	}

	public String getDisplayValue(List<String> displayLanguages) {
		for (String language : displayLanguages) {
			String aux = StringUtil.trimToEmpty(i18nValues.get(language));
			if (StringUtil.isNotEmpty(aux)) {
				return aux;
			}
		}
		return StringUtil.trimToEmpty(getDefaultValue());
	}

	public String getValueByLanguage(String language) {
		return StringUtil.trimToEmpty(i18nValues.get(language));
	}

	/*
	 * The hash is calculated considering two points: - Keys are sorted
	 * alphabetically - Only non empty values are considerated
	 */
	public String getHash() {
		StringBuilder sb = new StringBuilder();
		TreeSet<String> sortedSet = new TreeSet<String>(new AlphabeticalComparator());
		sortedSet.addAll(i18nValues.keySet());
		Iterator<String> iterator = sortedSet.iterator();
		while (iterator.hasNext()) {
			String key = iterator.next();
			String value = i18nValues.get(key);
			if (StringUtil.isNotEmpty(value)) {
				sb.append(StringUtil.trimToEmpty(key) + SeparatorUtil.AROBAS_SEPARATOR + StringUtil.trimToEmpty(value) + SeparatorUtil.PIPE_SEPARATOR);
			}
		}
		return sb.toString();
	}

	/**
	 * Return true if no real value has been set for at least one language
	 * 
	 * @return
	 */
	public boolean isEmpty() {
		StringBuilder sb = new StringBuilder();
		Iterator<Entry<String, String>> iterator = i18nValues.entrySet().iterator();
		while (iterator.hasNext()) {
			Entry<String, String> entry = iterator.next();
			sb.append(StringUtil.trimToEmpty(entry.getValue()));
		}
		return StringUtil.isEmpty(sb.toString());
	}

}
